package com.douqu.game.main.server.entity;

import com.alibaba.fastjson.JSONObject;
import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.E_ServerType;
import com.douqu.game.core.entity.battle.BattleDetail;
import com.douqu.game.core.entity.battle.BattleInitParam;
import com.douqu.game.core.factory.CodeFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.netty.NettyConnection;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.main.GameServer;
import com.douqu.game.main.msg.param.StartBattleParam;
import com.douqu.game.main.server.WorldManager;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2018-03-07 17:24
 */
public class ServerInfoBattle extends ServerInfo
{
    /**
     * 请求了战斗还没连接战斗服务器的
     */
    private Map<String, StartBattleParam> startBattleParamMap = new ConcurrentHashMap<>();

    private List<BattleDetail> battleList = new CopyOnWriteArrayList<>();
    /**
     * 添加战斗的记录
     */
//    private List<String> addBattleRecordList = new CopyOnWriteArrayList<>();
    private Map<String, Long> addBattleRecordMap = new ConcurrentHashMap<>();

//    private Map<String, BattleDetail> battleMap = new ConcurrentHashMap<>();

    public ServerInfoBattle(E_ServerType serverType, NettyConnection connection, int port)
    {
        super(serverType, connection, port);
    }

    @Override
    public void update()
    {
        PlayerController playerController = null;
        for(Map.Entry<String, StartBattleParam> entry : startBattleParamMap.entrySet())
        {
            if(entry.getValue().isOverdue())
            {
                playerController = GameServer.getInstance().getWorldManager().getPlayerController(entry.getValue().getPlayerIndex());
                if(playerController != null)
                {
                    playerController.clearBattle();
                }
                LogUtils.warn("通知了战斗服务器,一直没有收到回复,删除 -> " + entry.getValue());
                removeStartBattleParam(entry.getKey());
            }
        }

        final long currentTime = DataFactory.currentTime;
        for(Map.Entry<String, Long> entry : addBattleRecordMap.entrySet())
        {
            if(currentTime - entry.getValue() >= 60000)
            {
                addBattleRecordMap.remove(entry.getKey());
            }
        }
    }

    /**
     * 向战斗服务器发送战斗创建消息
     * @param battleId
     * @param battleType
     * @param playerIndex
     * @param targetIndex
     */
    public void sendBattleInit(String battleId, int battleType, int battleDetailType, String playerIndex, String targetIndex,  BattleInitParam battleInitParam)
    {
        if(connection == null)
            return;

        int serverId = GameServer.getInstance().getServerId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CodeFactory.KEY_BATTLE_ID, battleId);
        jsonObject.put(CodeFactory.KEY_BATTLE_TYPE, battleType);
        jsonObject.put(CodeFactory.KEY_BATTLE_DETAIL_TYPE, battleDetailType);
        jsonObject.put(CodeFactory.KEY_PLAYER_INDEX, playerIndex);
        jsonObject.put(CodeFactory.KEY_PLAYER_SERVER_ID, serverId);
        jsonObject.put(CodeFactory.KEY_TARGET_INDEX, targetIndex);
        jsonObject.put(CodeFactory.KEY_TARGET_SERVER_ID, serverId);
        if(battleInitParam != null)
            jsonObject.put(CodeFactory.KEY_PARAM, JSONObject.toJSONString(battleInitParam));

        ByteBuffer buffer = new ByteBuffer();

        buffer.writeUTF(jsonObject.toJSONString());

        connection.sendMsg(CodeFactory.BATTLE_INIT, buffer.getBytes());

        LogUtils.debug("通知战斗服务器创建战斗了 -> connection.id:" + connection.getId() + connection.getChannel().remoteAddress());
    }


    public void addStartBattleParam(StartBattleParam param)
    {
        startBattleParamMap.put(param.getBattleId(), param);
    }

    public StartBattleParam getStartBattleParam(String battleId)
    {
        return startBattleParamMap.get(battleId);
    }

    public void removeStartBattleParam(String battleId)
    {
        startBattleParamMap.remove(battleId);
    }

    public void addBattle(BattleDetail battle)
    {
        if(addBattleRecordMap.get(battle.getId()) != null)
            return;

        battleList.add(battle);
        addBattleRecordMap.put(battle.getId(), DataFactory.currentTime);

//        int index = battleList.indexOf(battle);
//        if(index < 0)
//        {
//            //里面没有才加
//            battleList.add(battle);
//            addBattleRecordList.add(battle.getId());
//        }
//        if(battleMap.get(battle.getId()) == null)
//        {
//            battleMap.put(battle.getId(), battle);
//            battleList.add(battle);
//        }
    }

    public void removeBattle(BattleDetail battle)
    {
//        battleMap.remove(battle.getId());
        battleList.remove(battle);
    }

    public BattleDetail getBattle(String battleId)
    {
        BattleDetail battleDetail = new BattleDetail(0, null);
        battleDetail.setId(battleId);

        int index = battleList.indexOf(battleDetail);
        return index >= 0 ? battleList.get(index) : null;
    }

    public BattleDetail getBattle(BattleDetail battleDetail)
    {
        int index = battleList.indexOf(battleDetail);
        return index >= 0 ? battleList.get(index) : null;
    }


    public boolean isHaveAddRecord(BattleDetail battleDetail)
    {
        return addBattleRecordMap.get(battleDetail.getId()) != null;
    }

    @Override
    public void destroy()
    {
        WorldManager worldManager = GameServer.getInstance().getWorldManager();
        PlayerController playerController = null;
        for(BattleDetail info : battleList)
        {
            playerController = worldManager.getPlayerController(info.getTeam1Info().getIndexInfo());
            if(playerController != null)
            {
                playerController.clearBattle();
            }
            playerController = worldManager.getPlayerController(info.getTeam2Info().getIndexInfo());
            if(playerController != null)
            {
                playerController.clearBattle();
            }
        }

    }


    public int getBattleCount() {
        return battleList.size();
    }

    public List<BattleDetail> getBattleList()
    {
        return battleList;
    }
}
